package api

import (
	"net/url"
	"strconv"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/plugin/gva_intelligent_form/model/request"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type IntelligentFormSubmissionApi struct{}

// SubmitForm 提交表单
// @Tags IntelligentFormSubmission
// @Summary 提交表单
// @accept application/json
// @Produce application/json
// @Param data body request.SubmitFormRequest true "提交表单"
// @Success 200 {object} response.Response{msg=string} "提交成功"
// @Router /intelligent-form/public/submit [post]
func (api *IntelligentFormSubmissionApi) SubmitForm(c *gin.Context) {
	var req request.SubmitFormRequest
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 获取用户ID（可能为空，匿名提交）
	var userID *uint
	if id := utils.GetUserID(c); id != 0 {
		userID = &id
	}

	// 获取客户端IP
	ip := c.ClientIP()

	err = intelligentFormSubmissionService.SubmitForm(&req, userID, ip)
	if err != nil {
		global.GVA_LOG.Error("提交失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithMessage("提交成功", c)
}

// GetSubmissionList 获取提交记录列表
// @Tags IntelligentFormSubmission
// @Summary 获取提交记录列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.IntelligentFormSubmissionSearch true "获取提交记录列表"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "获取成功"
// @Router /intelligent-form/submission/list [get]
func (api *IntelligentFormSubmissionApi) GetSubmissionList(c *gin.Context) {
	var pageInfo request.IntelligentFormSubmissionSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	list, total, err := intelligentFormSubmissionService.GetSubmissionList(pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}

	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

// GetSubmission 获取提交记录详情
// @Tags IntelligentFormSubmission
// @Summary 获取提交记录详情
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param id query uint true "提交记录ID"
// @Success 200 {object} response.Response{data=model.IntelligentFormSubmission,msg=string} "查询成功"
// @Router /intelligent-form/submission/detail [get]
func (api *IntelligentFormSubmissionApi) GetSubmission(c *gin.Context) {
	idStr := c.Query("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		response.FailWithMessage("参数错误", c)
		return
	}

	submission, err := intelligentFormSubmissionService.GetSubmission(uint(id))
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
		return
	}

	response.OkWithData(submission, c)
}

// DeleteSubmission 删除提交记录
// @Tags IntelligentFormSubmission
// @Summary 删除提交记录
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param id query uint true "提交记录ID"
// @Success 200 {object} response.Response{msg=string} "删除成功"
// @Router /intelligent-form/submission/delete [delete]
func (api *IntelligentFormSubmissionApi) DeleteSubmission(c *gin.Context) {
	idStr := c.Query("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		response.FailWithMessage("参数错误", c)
		return
	}

	err = intelligentFormSubmissionService.DeleteSubmission(uint(id))
	if err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
		return
	}

	response.OkWithMessage("删除成功", c)
}

// ExportSubmissions 导出提交数据
// @Tags IntelligentFormSubmission
// @Summary 导出提交数据
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query request.ExportSubmissionRequest true "导出提交数据"
// @Success 200 {object} response.Response{msg=string} "导出成功"
// @Router /intelligent-form/submission/export [get]
func (api *IntelligentFormSubmissionApi) ExportSubmissions(c *gin.Context) {
	var req request.ExportSubmissionRequest
	err := c.ShouldBindQuery(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 解码URL编码的参数
	if req.ExportType != "" {
		req.ExportType, _ = url.QueryUnescape(req.ExportType)
	}

	var formID *uint
	if req.FormID != 0 {
		formID = &req.FormID
	}

	startDate := ""
	endDate := ""
	if req.StartTime != nil {
		startDate = req.StartTime.Format("2006-01-02")
	}
	if req.EndTime != nil {
		endDate = req.EndTime.Format("2006-01-02")
	}

	fileData, fileName, err := intelligentFormSubmissionService.ExportSubmissions(formID, startDate, endDate)
	if err != nil {
		global.GVA_LOG.Error("导出失败!", zap.Error(err))
		response.FailWithMessage("导出失败", c)
		return
	}

	c.Header("Content-Type", "application/octet-stream")
	c.Header("Content-Disposition", "attachment; filename="+fileName)
	c.Header("Content-Transfer-Encoding", "binary")
	c.Data(200, "application/octet-stream", fileData)
}

// SubmitGeneratedForm 提交生成的表单（无需认证）
// @Tags IntelligentFormSubmission
// @Summary 提交生成的表单
// @accept application/json
// @Produce application/json
// @Param data body request.SubmitFormRequest true "提交表单"
// @Success 200 {object} response.Response{msg=string} "提交成功"
// @Router /intelligent-form/generated/submit [post]
func (api *IntelligentFormSubmissionApi) SubmitGeneratedForm(c *gin.Context) {
	var req request.SubmitFormRequest
	err := c.ShouldBindJSON(&req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 获取客户端IP
	ip := c.ClientIP()

	// 生成表单的提交始终为匿名提交
	err = intelligentFormSubmissionService.SubmitGeneratedForm(&req, ip)
	if err != nil {
		global.GVA_LOG.Error("提交失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithMessage("提交成功", c)
}
